use std::time::Duration;
use config::{Config, ConfigError, File, Value};
use serde::Deserialize;
use std::path::PathBuf;
use clap::Parser;
use crate::cli::Cli;
use std::collections::HashMap;

#[derive(Debug, Deserialize)]
pub struct ServerConfig {
    host: String,
    port: u16,
}

#[derive(Debug, Deserialize)]
pub struct PeerConfig {
    host: String,
    port: u16,
}

#[derive(Debug, Deserialize)]
pub struct GossipConfig {
    sync_interval_secs: u64,
}

#[derive(Debug, Deserialize)]
pub struct DbConfig {
    path: String,
}

#[derive(Debug, Deserialize)]
pub struct Settings {
    server: ServerConfig,
    peers: Vec<PeerConfig>,
    gossip: GossipConfig,
    db: DbConfig,
}

impl Settings {
    pub fn new() -> Result<Self, ConfigError> {
        // 解析命令行参数
        let cli = Cli::parse();

        // 从配置文件加载基础配置
        let mut builder = Config::builder()
            .add_source(File::with_name(&cli.config));

        // ... (其他覆盖逻辑保持不变)

        if let Some(peers) = cli.peers {
            // 解析peers字符串 "host:port,host:port"
            let peer_maps: Vec<HashMap<String, Value>> = peers.split(',')
                .filter_map(|addr| {
                    let parts: Vec<&str> = addr.trim().split(':').collect();
                    if parts.len() == 2 {
                        if let Ok(port) = parts[1].parse::<u16>() {
                            let mut peer_map = HashMap::new();
                            peer_map.insert("host".to_string(), parts[0].into());
                            peer_map.insert("port".to_string(), i64::from(port).into());
                            return Some(peer_map);
                        }
                    }
                    None
                })
                .collect();

            // 将 Vec<HashMap<...>> 包装在单个 Value::new(...) 中
            // 这是关键的修复
            builder = builder.set_override("peers", Value::new(None, peer_maps))?;
        }

        let config = builder.build()?;
        println!("Loading config from: {}", cli.config);
        config.try_deserialize()
    }

    pub fn get_server_addr(&self) -> String {
        format!("{}:{}", self.server.host, self.server.port)
    }

    pub fn get_peer_addrs(&self) -> Vec<String> {
        self.peers
            .iter()
            .map(|p| format!("{}:{}", p.host, p.port))
            .collect()
    }

    pub fn get_sync_interval(&self) -> Duration {
        Duration::from_secs(self.gossip.sync_interval_secs)
    }

    pub fn get_db_path(&self) -> PathBuf {
        PathBuf::from(&self.db.path)
    }
}